<template>
  <div style="margin-left: 2%;margin-right: 2%">

    <div v-if="showContractApprove">
      <el-card>
        <span style="font-size: 13px">项目编号：{{this.selectedProject.projectCode}}</span>
        <span style="font-size: 13px;margin-left: 3%">项目名称：{{this.selectedProject.projectName}}</span>
        <span style="font-size: 13px;margin-left: 3%">项目预算：{{this.selectedProject.budget}} 元</span>
<!--        <span style="font-size: 13px;margin-left: 3%">采购类别：{{this.selectedProject.purchaseCategoryId}}-->
        <span style="font-size: 13px;margin-left: 3%">采购类别：
          {{
            this.selectedProject.purchaseCategoryId === 1 ? "货物类" :
            this.selectedProject.purchaseCategoryId === 2 ? "服务类" :
            this.selectedProject.purchaseCategoryId === 3 ? "工程类" :
            "未知类别"
          }}
        </span>
      </el-card>
      <el-card  v-if="supplierTable && supplierTable.length > 0">
        <span style="font-size: 13px;margin-left: 3%">成交供应商：{{this.supplierTable[0].supplierName}}</span>
        <span style="font-size: 13px;margin-left: 3%">报价排名：{{this.supplierTable[0].priceRanking}}</span>
        <span style="font-size: 13px;margin-left: 3%">报价：{{this.supplierTable[0].price}} 元
                </span>
      </el-card>
      <el-card v-else>
        <span style="font-size: 13px;margin-left: 3%">成交供应商：未查询到</span>
        <span style="font-size: 13px;margin-left: 3%">报价排名：未查询到</span>
        <span style="font-size: 13px;margin-left: 3%">报价：未查询到</span>
        暂无数据
      </el-card>

      <div style="margin-top: 14px;margin-bottom: 10px">
        <el-table
            :data="contractTable"
            border
            style="width: 100%">
          <el-table-column
              prop="generateDate"
              min-width="100px"
              label="生成时间"
          >
          </el-table-column>
          <el-table-column
              prop="filename"
              min-width="150px"
              label="文件名"
          >
          </el-table-column>

          <el-table-column
              prop="controls"
              width="100px"
              label="操作"
          >
            <template slot-scope="{$index,row}">
              <i  title="下载" @click="handledownload(row)" style="color: #1e90ff;margin-right: 10px;cursor: pointer">下载</i>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="font-size: 13px;margin-left: 19px;margin-top: 30px;display: block">
        <span style="vertical-align: top">审批意见：</span>
        <el-input v-model="approveSuggestion" placeholder="输入内容" style="width: 540px" type="textarea" :rows="3"></el-input>
      </div>

      <div style="font-size: 15px;margin-top: 20px;">审批状态：{{selectedProject.contractApproveStatus}}</div>

      <div style="margin-left: 220px;margin-top: 30px;">
                <span>
                  <el-button @click="showApproveSubmitDialog" :disabled="selectedProject.accSubstatus === '已提交' || selectedProject.contractApproveStatus === '退回' || selectedProject.contractApproveStatus === '审批通过'" type="primary">审批通过</el-button>
                </span>
        <span style="margin-left: 40px;">
                  <el-button @click="showApproveReturnDialog" :disabled="selectedProject.accSubstatus === '已提交'" type="primary">退 回</el-button>
                </span>
        <span style="margin-left: 40px;">
                  <el-button @click="goback" type="primary">返回</el-button>
                </span>
      </div>
    </div>


    <div v-else>
      <el-card>
        <span style="font-size: 13px">项目编号：</span>
        <el-input  v-model="search.projectCode" placeholder="输入内容" style="width: 130px"></el-input>
        <span style="font-size: 13px;margin-left: 1%">项目名称：</span>
        <el-input  v-model="search.projectName" placeholder="输入内容" style="width: 130px"></el-input>
        <span style="font-size: 13px;margin-left: 1%">采购类别：</span>
        <el-select v-model="search.purchaseCategoryId"  placeholder="请选择" style="width: 130px">
          <el-option label="货物类" value="1"></el-option>
          <el-option label="服务类" value="2"></el-option>
          <el-option label="工程类" value="3"></el-option>
        </el-select>
        <span style="font-size: 13px;margin-left: 1%">成交合同审批状态：</span>
        <el-select v-model="search.contractApproveStatus"  placeholder="请选择" style="width: 130px">
          <el-option label="未审批" value="未审批"></el-option>
          <el-option label="审批通过" value="审批通过"></el-option>
          <el-option label="退回" value="退回"></el-option>
        </el-select>
        <div style="display: inline;margin-left: 1%">
          <el-button  size="mini" type="primary" @click="searchConditon">查询</el-button>
          <el-button size="mini" @click="clearMes">清空查询</el-button>
        </div>
      </el-card>

      <div style="margin-top: 7px;margin-bottom: 10px">

        <el-table :data="userTable" border v-loading="loading" style="width: 100%">
          <!-- 其他列 -->

          <el-table-column
              prop="projectCode"
              min-width="30px"
              label="项目编号"
          >
          </el-table-column>

          <el-table-column
              prop="createTime"
              min-width="50px"
              label="创建时间"
          >
          </el-table-column>
          <el-table-column
              prop="projectName"
              min-width="80px"
              label="项目名称"
          >
          </el-table-column>
          <el-table-column
              prop="purchaseCategoryId"
              min-width="30px"
              label="采购类别"
          >
            <template slot-scope="scope">
              <!-- 根据采购类别的值显示不同文本 -->
              <span v-if="scope.row.purchaseCategoryId === 1">货物类</span>
              <span v-else-if="scope.row.purchaseCategoryId === 2">服务类</span>
              <span v-else-if="scope.row.purchaseCategoryId === 3">工程类</span>
              <span v-else>其他采购类别</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="purchaseMethod"
              min-width="30px"
              label="采购方式"
          >
          </el-table-column>
          <el-table-column
              prop="budget"
              min-width="30px"
              label="预算金额(元)">
          </el-table-column>

          <el-table-column
              prop="contractApproveStatus"
              min-width="30px"
              label="成交合同审批状态">
          </el-table-column>

          <!--        时间可能有问题-->
          <el-table-column
              prop="contractApproveTime"
              min-width="50px"
              label="审批通过时间">
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template slot-scope="{$index,row}">
              <i  title="项目管理" @click="goToContractApprove(row)" style="color: dodgerblue;cursor: pointer">合同审批</i>
            </template>
          </el-table-column>

        </el-table>

        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="thisData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>



    </div>
  </div>
</template>

<script>

import {getAllProjectNeedApprove, reqContractConditionSer, reqApproveGetContract, reqsubmitContractApprove, reqreturnContractApprove, reqContractSupplierQuotation, downloadContractApprove} from "@/api/contractApprove";
import {reqApproveCheck, reqApproveSubmit} from "@/api/purchaseItemManage";
import downloadFile from "@/utils/downloadFile";

// import {reqApproveGetContractet, reqGetAllItems} from "@/api/purchaseItemManage";


export default {

  mounted() {
    this.getAllProjectNA()
  },

  methods: {

    //跳转到成交合同审批
    async goToContractApprove(row) {
      this.selectedProject = row
      this.showContractApprove = true
      // await this.getPurchaseList(row.projectId)
      this.ProjectId = row.projectId
      this.approveSuggestion = row.contractApproveSuggestion
      //获取成交合同数据
      await this.approveGetContract(row.projectId)
      //获取成交供应商数据
      await this.ContractSupplierQuotation(row.projectId)
      // await this.approveGet()
      // this.QuaSubmitStatus = row.quaSubmitStatus
      // this.QuaApproveStatus = row.quaApproveStatus
    },

    //获取成交供应商
    // async ContractSupplierQuotation(projectId) {
    //   const data = { projectId };
    //   let res = await reqContractSupplierQuotation(data)
    //   if(res.data.code===200){
    //     const dataArray = Object.values(res.data.data);
    //     this.supplierTable = dataArray.filter(item => item.priceRanking === 1);
    //     // this.supplierTable = res.data.data.filter(item => item.priceRanking === 1);
    //     console.log(this.supplierTable);
    //   }else {
    //     this.$message.error(res.data.msg);
    //   }
    // },
    async ContractSupplierQuotation(projectId) {
      const data = { projectId };
      try {
        const res = await reqContractSupplierQuotation(data);
        if (res.data.code === 200) {
          const result = res.data.data;
          console.log(res.data.data);
          if (result.quotations && result.quotations.length > 0) {
            // 只获取第一条数据
            this.supplierTable = [result.quotations[0]];
            console.log(this.supplierTable);
          } else {
            this.supplierTable = [];
          }
        } else {
          this.$message.error(res.data.msg);
        }
      } catch (error) {
        console.error(error);
        this.$message.error("请求失败，请重试！");
      }
    },


    //获取成交合同数据
    async approveGetContract(projectId) {
      let res = await reqApproveGetContract(projectId)
      if(res.data.code===200){
        this.contractTable = res.data.data
      }else {
        this.$message.error(res.data.msg);
      }
    },

    //审批通过
    async approveSubmit() {
      const inputObj = {
        projectId: this.ProjectId,
        contractApproveSuggestion: this.approveSuggestion,

      };
      let res = await reqsubmitContractApprove(inputObj)
      if(res.data.code===200){
        this.$message({
          type: 'success',
          message: '提交成功!'
        });
        this.goback()
      }else {
        this.$message.error(res.data.msg);
      }
      // await this.approveGet()
    },

    //审批退回
    async approveReturn() {
      const inputObj = {
        projectId: this.ProjectId,
        contractApproveSuggestion: this.approveSuggestion,

      };
      let res = await reqreturnContractApprove(inputObj)
      if(res.data.code===200){
        this.$message({
          type: 'success',
          message: '提交成功!'
        });
        this.goback()
      }else {
        this.$message.error(res.data.msg);
      }
      // await this.approveGet()
    },

    async showApproveSubmitDialog() {
      this.$confirm('确认要执行审批通过操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.approveSubmit();
      }).catch(() => {
        // 用户点击了取消按钮
            this.$message({
              type: 'info',
              message: '已取消审批'
            });
      });
    },

    async showApproveReturnDialog() {
      this.$confirm('确认要执行审批退回操作吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.approveReturn();
      }).catch(() => {
        // 用户点击了取消按钮
        this.$message({
          type: 'info',
          message: '已取消审批'
        });
      });
    },


    //返回
    handleRefresh() {
      location.reload(); // 刷新当前页面
    },

    //返回上一级
    goback(){
      this.search.projectCode=''
      this.search.projectName=''
      this.search.purchaseCategoryId=''
      this.search.contractApproveStatus=''

      this.approveData.projectId=''
      this.approveData.quacondition=''
      this.approveData.serviceProjectContent=''
      this.approveData.projectDuration=''
      this.approveData.deliveryPlace=''
      this.approveData.deliveryTime=''
      this.approveData.maintenancePeriod=''
      this.approveData.projectAfterSale=''
      this.approveData.payMethod=''
      this.currentPage=1
      this.centerDialogVisible=false
      this.editDialogVisible=false
      this.showPageSearch=false
      this.showContractApprove=false
      this.selectedProject=null
      this.selectedSupplier=null
      this.ProjectId=''
      this.approveSuggestion=''
      this.loading=true
      this.userTable=[]
      this.contractTable=[]
      this.supplierTable=[]
      this.total=0, this.thisData.page = 1
      this.thisData.pageSize = 20

      this.getAllProjectNA()
    },

    //获取所有需要审批项目
    async getAllProjectNA(){
      this.loading = true
      let data = this.currentPage + '/' + this.thisData.pageSize
      console.log(this.currentPage);
      console.log(this.thisData.pageSize);
      let res = await getAllProjectNeedApprove(data)
      if (res) {
        this.loading = false
      }
      if (res.data.code === 200) {
        this.userTable = res.data.data.record
        this.total = res.data.data.total
      } else {
        this.$message({
          message: `${res.data.data.msg}`,
          type: 'warning'
        });
      }
    },

    //点击下载文件
    async handledownload(row) {
      console.log(row.id);
      this.$message.success("正在拼命下载请稍后")
      let res = await downloadContractApprove(row.id)
      downloadFile(res,row.filename)

    },

    //条件查询项目
    async searchConditon() {
      this.loading = true
      let theDatas = {
        pageSize: this.thisData.pageSize,
        page: this.thisData.page,
        projectCode: this.search.projectCode,
        projectName: this.search.projectName || '',
        purchaseCategoryId: this.search.purchaseCategoryId,
        contractApproveStatus: this.search.contractApproveStatus,
      }
      let pageInfo = this.currentPage + "/" + this.thisData.pageSize
      let res = await reqContractConditionSer(pageInfo, theDatas)
      this.showPageSearch = true
      if (res) {
        this.loading = false
      }
      if (res.data.code === 200) {
        this.userTable = res.data.data.record;
        this.total = res.data.data.total
      } else {
        this.userTable = [];
        this.total = 0;
        this.$message(res.data.msg);
      }
    },
    clearMes() {
      this.showPageSearch = false
      Object.keys(this.search).forEach(index => this.search[index] = '')
    },

    handleSizeChange(val) {
      this.thisData.pageSize = val
      this.getAllProjectNA()

    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getAllProjectNA()
    },
  },

  created() {

  },

  data() {
    return {
      search:{
        projectCode:'',
        projectName:'',
        purchaseCategoryId:'',
        contractApproveStatus:''
      },
      rules: {
        keyname: [{required: true, message: '请输入', trigger: ['blur', 'change']}],
      },
      tableData: [

      ],
      approveData: {
        projectId: '',
        quacondition: '',
        serviceProjectContent: '',
        projectDuration: '',
        deliveryPlace:'',
        deliveryTime: '',
        maintenancePeriod:'',
        projectAfterSale:'',
        payMethod:'',
      },
      currentPage: 1,
      centerDialogVisible: false,
      editDialogVisible: false,
      showPageSearch: false,
      showContractApprove: false,
      selectedProject: null,
      selectedSupplier: null,
      ProjectId:'',
      approveSuggestion:'',
      loading: true,
      userTable: [],
      contractTable: [],
      supplierTable: [],
      total: 0,
      thisData: {
        page: 1,
        pageSize: 20,
      },
    }
  },

}
</script>
